class BooksController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  include AuthenticatedSystem

  # If you want "remember me" functionality, add this before_filter to Application Controller
  before_filter :login_admin_required, :only => [ :edit, :update, :destroy, :create, :new ]

  def index
    list
    render :action => 'list'
  end

  def search
		@phrase = params[:inx].delete('*')
    if !@phrase.empty?			
      @books = Book.find_using_term(@phrase)
    else
      @books =[]
    end
    @book_pages, @books = paginate_collection @books, :page => params[:page]
    render :action => 'list'
  end


  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @conditions = ["state <> ?", Book::STATE_BLOCKED]
    if !params[:category_id].nil?
      @conditions = ["category_id = ?", params[:category_id]]
      params[:category_id] = nil
    end

    if !params[:language_id].nil?
      @conditions = ["language_id = ?", params[:language_id]]
      params[:language_id] = nil
    end

    if !params[:state].nil?
      @conditions = ["state = ?", params[:state]]
      params[:state] = nil
    end

    @book_pages, @books = paginate(:books, :conditions => @conditions, :order => 'title, author', :per_page => 10)
  end

  def show
    @book = Book.find(params[:id])
  end

  def new
    @book = Book.new
  end

  def create
    @book = Book.new(params[:book])
    @book.state = Book::STATE_AVAILABLE
    if @book.save
      flash[:notice] = 'Book was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @book = Book.find(params[:id])
  end

  def update
    @book = Book.find(params[:id])
    if @book.update_attributes(params[:book])
      flash[:notice] = 'Book was successfully updated.'
      redirect_to :action => 'list'
    else
      render :action => 'edit'
    end
  end

  def destroy
    @book = Book.find(params[:id])
    if @book.can_destroy?
      @book.destroy
      flash[:notice] = 'Book destroyed'
    else
      flash[:warning] = 'Book cannot be destroyed related Borrowings exists'
    end
    redirect_to :action => 'list'
  end
  
  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options

    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end
end
